__author__ = 'ZhangJian'
import requests
import time
import sys
import os
import ast
from bs4 import BeautifulSoup
from subprocess import Popen

reload(sys)
sys.setdefaultencoding('utf-8')
'''
    login module
'''

COOKIE_FILE = "cookies"
HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36',
    'Host': 'www.zhihu.com',
    'Origin': 'http://www.zhihu.com',
    'Connection': 'keep-alive',
    'Referer': 'http://www.zhihu.com/',
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-Requested-With': 'XMLHttpRequest'
}
LOGIN_URL = "http://www.zhihu.com/login/email"

CAPTURE_URL = 'http://www.zhihu.com/captcha.gif?r='


class Index():
    def __init__(self, email, password):
        # declare global session
        self.session = requests.session()
        self.cookies = {}
        # construct data
        self.data = {
            "email": email,
            "password": password,
            "rememberme": "true"
        }

    def getXSRF(self):
        """
        get _xscf data
        """
        try:
            response = self.session.get("http://www.zhihu.com/#signin", headers=HEADERS)
            # format html
            soup = BeautifulSoup(response.text.encode('utf-8'))
            xsrf = str(soup.find_all("input")[0].get("value"))
        except:
            raise
        return xsrf

    def getCaptcha(self):
        """
            get captcha
        """
        timsstamp = str(int(time.time() * 1000))
        captcha_URL = CAPTURE_URL + timsstamp
        captcha = self.session.get(url=captcha_URL, headers=HEADERS)
        if not os.path.exists("captcha"):
            os.mkdir("captcha")
        # save captcha
        # @sys.path[0]
        try:
            with open("captcha\\" + timsstamp + '.gif', 'wb') as f:
                f.writelines(captcha.content)
            Popen("captcha\\" + timsstamp + '.gif', shell=True)
        except:
            raise '[!]Captha get failed,error from method of getCaptcha().'
        return str(raw_input("[+]input captcha:"))

    def login(self):
        """
        post to login
        """

        if os.path.exists("dat\\cookies.dat"):
            with open('dat\\cookies.dat', 'r') as cj:
                self.cookies = ast.literal_eval(str(cj.readline()))
                return self.cookies

        else:
            if not os.path.exists("dat"):
                os.mkdir("dat")

            self.data['_xsrf'] = self.getXSRF()
            # self.data['captcha'] = self.getCaptcha()

            req = self.session.post(url=LOGIN_URL, data=self.data, headers=HEADERS)
            print 'after login cookies :%s' % (self.session.cookies.get_dict())
            self.cookies = self.session.cookies.get_dict()
            with open('dat\\cookies.dat', 'wb') as cj:
                cj.write(str(self.session.cookies.get_dict()))
                cj.flush()
                cj.close()

            return req.text.decode("unicode_escape")


def main():
    i = Index('zhangjian12424@gmail.com', 'yuious123')
    print i.login()
    return i.cookies


# TEST
if __name__ == "__main__":
    main()
